package org.flashbrighton.as3bots.logic
{
	import org.flashbrighton.as3bots.events.BotEvent;
	import org.flashbrighton.as3bots.models.CollidableType;
	
	public class StusBotLogic implements IBotLogic
	{
		private var _engineVal:Number;
		private var _rotationVal:Number;
		
		private var _rotationDir:Number;
		
		private var _lastHitDir:Number = 0;
		private var _frame:Number = 0;
		private var _lastAttack:Number = 0;
//		private var
		
		private var _mode:String = "search";
		
		/**
		 * Modes:
		 * 
		 * Search, attack, retreat
		 * 
		 */
		public function StusBotLogic()
		{
			_engineVal = 0.5;
			_rotationVal = 0.4;
			_rotationDir = 0.1;
			trace("*** fight ***");
		}

		public function notify(event:BotEvent):void
		{
			if (event.targetType == CollidableType.WALL)
			{
				_engineVal *= -1;
				_rotationVal = -0.3;
				_mode = "retreat";
			}
			else
			{
				trace(event.collisionPoint);
				_lastHitDir = _rotationDir;
				_lastAttack = _frame;
				startRetreat();
				if (Math.abs(event.collisionPoint) > 0.5)
				{
					startRetreat();	
					_rotationDir = 0.4;
				}
				else
				{
					_rotationDir = -0.4;
					startAttack();
				}
				
			}
		}
		
		private function startAttack():void
		{
			_mode = "attack";
			_rotationDir = 0;
			_engineVal = 1.0;
		}
		
		private function startRetreat():void
		{
			_mode = "retreat";
			_rotationDir = -1;
			_engineVal *= -1;
		}
		
		public function run():void
		{
			_frame++;
			if (Math.abs(_rotationVal) < 0.5)
			{
				_rotationVal += _rotationDir;							
			}
			
			if (_mode == "search")
			{
				if (_rotationVal > 0.3)
				{
					_rotationDir = -0.01;
				}
				else if (_rotationVal < -0.3)
				{
					_rotationDir = 0.01;
				}
			}
			else if (_mode == "retreat")
			{
				_rotationDir = 0;
				_rotationVal = 0;
				
				if (_frame - _lastAttack > 50)
				{
					_mode = "search";
					_engineVal = 0.5;
					trace("Go search");
				}
			}
			
			else if (_mode == "attack")
			{
				if (_frame - _lastAttack > 100)
				{
					_mode = "search";
				}
				if (_rotationVal < _lastHitDir)
				{
					_rotationDir = 0.1;
				}
				else
				{
					_rotationDir = -0.1;
				}
			}
			
			if (_engineVal < 0.2)
			{
				_engineVal += 0.05;
			}
		}
		
		public function get enginePercent():Number
		{
			return _engineVal;
		}
		
		
		public function get rotatorPercent():Number
		{
			return _rotationVal;
		}
		
	}
}